import {ACT_ADD, ACT_CHANGE_TEXT, ACT_DEC, RECV_DATA, RECV_ERROR, RECV_TIMEOUT} from "../actions/actions";
// import {fetchDataThunk} from "../actions/thunk";
// import {combineReducers} from "redux";

//定义初始状态
export const initialState = {
    count: {
        num: 0
    },
    login: {
        name: 'hctec'
    },
    fetch: {
        data: [
            {name: 'cpp', unit: 5},
            {name: 'java', unit: 8}
        ],
        error: ''
    }
};

export function mainReducer(state=initialState, action) {
    return {
        count: count(state.count, action),
        login: login(state.login, action),
        fetch: fetch(state.fetch, action),
    };
}

//不建议这样使用，灵活性受限制，出现错误也不容易排查
// export const mainReducer = combineReducers({
//     count,
//     login
// });

function count(state, action) {
    switch(action.type){
        case ACT_ADD:
            // return {count: state.count+1, name: state.name};
            return Object.assign({}, state, {num: state.num+1});
        case ACT_DEC:
            // return {count: state.count-1, name: state.name};
            return Object.assign({}, state, {num: state.num-1});
        default:
            return state;
    }
}

function login(state, action){
    switch(action.type){
        case ACT_CHANGE_TEXT:
            return Object.assign({}, state, {name: action.payload.value});
        default:
            return state;
    }
}

function fetch(state, action){
    switch (action.type){
        case RECV_DATA:
            return Object.assign({}, state, {data: action.data, error: ''});
        case RECV_ERROR:
            return Object.assign({}, state, {error: action.message});
        case RECV_TIMEOUT:
            return Object.assign({}, state, {error: action.message});
        default:
            return state;
    }
}
